﻿using System;
using System.Web;
using System.Data.SqlClient;
using System.Collections.Specialized;
using System.Configuration;
using System.Web.Configuration;
using System.Collections.Generic;
using System.Configuration.Provider;
using System.Security.Permissions;
using System.Data.Common;
using System.Data;
using System.Text;
using System.Xml;
using Openfree.Framework.TypeDataSet;

/// <summary>
/// Summary description for SiteMapProvider
/// </summary>
public class SiteMapProviderEx : StaticSiteMapProvider
{
    private SiteMapNode _root;
    private List<string> urlList = new List<string>();


    public override void Initialize(string name, NameValueCollection attributes)
    {
        base.Initialize(name, attributes);
    }

    public override SiteMapNode BuildSiteMap()
    {
        return null;
    }

    public SiteMapNode BuildSiteMapEx()
    {
        lock (this)
        {
            //if (_root != null)
            //    return _root;
            try
            {
                urlList.Clear();

                //完全从数据库中读取菜单
                //_root = new SiteMapNode(this, "root", "url", "title");
                //AddNode(_root, null);
                //CreateSitemap(SessionManager.DataSetRule, "0", _root);

                //从配置文件中读取菜单
                XmlDocument xmlDoc;
                if (HttpContext.Current.Application["SiteMap"] == null)
                {
                    string webConfig = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
                    webConfig += "web.config";
                    xmlDoc = new XmlDocument();
                    xmlDoc.Load(webConfig);
                    //xpath 大小写敏感
                    string defaultProvider = xmlDoc.SelectSingleNode("/configuration/system.web/siteMap").Attributes["defaultProvider"].Value;
                    string fileName = xmlDoc.SelectSingleNode("/configuration/system.web/siteMap/providers/add[@name='" + defaultProvider
                        + "']").Attributes["siteMapFile"].Value;
                    string sitemap = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + fileName;
                    xmlDoc.Load(sitemap);
                    HttpContext.Current.Application["SiteMap"] = xmlDoc;
                }
                xmlDoc = HttpContext.Current.Application["SiteMap"] as XmlDocument;
                _root = null;
                Clear();
                
                _root = new SiteMapNode(this, "root", "", "");
                AddNode(_root, null);
                LoadSitemap(SessionManager.DataSetRule, xmlDoc.ChildNodes[1].ChildNodes[0], _root);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.ToString());
            }
            finally
            {
            }
            return _root;
        }
    }



    protected override SiteMapNode GetRootNodeCore()
    {
        lock (this)
        {
            return BuildSiteMapEx();
        }
    }


    private void LoadSitemap(DataSet dsRule, XmlNode xmlNode, SiteMapNode parentNode)
    {
        foreach (XmlNode childNode in xmlNode.ChildNodes)
        {
            if ("#comment".Equals(childNode.Name))
            {
                continue;
            }


            string url = string.Empty;
            string title = string.Empty;
            if (childNode.Attributes["url"] != null)
            {
                url = childNode.Attributes["url"].Value;
            }
            if (childNode.Attributes["title"] != null)
            {
                title = childNode.Attributes["title"].Value;
            }

            if (url == string.Empty && dsRule.Tables[0].Select("Subject='" + title + "'").Length == 0)
            {
                continue;
            }
            else if (dsRule.Tables[0].Select("ContainerName='" + url + "'").Length == 0)
            {
                continue;
            }


            if (url != string.Empty && urlList.Exists((c) => { return c.Equals(url); }))
            {
                continue;
            }
            urlList.Add(url);


            if (url != string.Empty)
            {
                url = "~/" + url;
            }

            if (!childNode.HasChildNodes)
            {
                SiteMapNode node = new SiteMapNode(this, Guid.NewGuid().ToString(),
                    url, childNode.Attributes["title"].Value, childNode.Attributes["title"].Value);
                AddNode(node, parentNode);
            }
            else
            {
                SiteMapNode node = new SiteMapNode(this, Guid.NewGuid().ToString(),
                    url, childNode.Attributes["title"].Value, childNode.Attributes["title"].Value);

                AddNode(node, parentNode);
                LoadSitemap(dsRule, childNode, node);
            }
        }
    }

    private void CreateSitemap(DataSet dsRule, string ParentID, SiteMapNode parentNode)
    {
        foreach (DataRow row in dsRule.Tables[0].Select("ParentID='" + ParentID + "' and Category='SITEADMIN'"))
        {
            if (row["ContainerName"].ToString()!= string.Empty && urlList.Exists((c) => { return c.Equals(row["ContainerName"].ToString()); }))
            {
                continue;
            }
            urlList.Add(row["ContainerName"].ToString());

            if (row["HasChild"].ToString() == "0")
            {
                SiteMapNode node = new SiteMapNode(this, row["NodeID"].ToString(), 
                    row["ContainerName"].ToString(), row["Subject"].ToString(), row["Subject"].ToString());
                AddNode(node, parentNode);
            }
            else
            {
                SiteMapNode node = new SiteMapNode(this, row["NodeID"].ToString(), 
                    row["ContainerName"].ToString(), row["Subject"].ToString(), row["Subject"].ToString());
                AddNode(node, parentNode);
                CreateSitemap(dsRule, row["NodeID"].ToString(), node);
            }
        }
    }

}



